import os
import sqlite3
import logging
import random
import hashlib
from inc import *
root=os.path.dirname(os.path.realpath(__file__))
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s -%(levelname)s -%(process)d -%(module)s -%(funcName)s -%(message)s')

logging.debug(root)
db=sqlite3.connect(root+"/test.db")
try:
    db.execute('create table hash (path varchar(256) primary key, hash varchar(128))')
except (sqlite3.Error,Exception) as e:
    logging.error("Database error: %s" % e)
    db.rollback()
else :
    db.commit()


def inserts(db,path,hash):
    try :
        db.execute("INSERT INTO hash (path,hash) VALUES ('%s', '%s' )"%(path,hash))       
    except (sqlite3.Error,Exception) as e:
        logging.error("Database error: %s" % e)
        db.rollback()
    else :
        db.commit()
        logging.debug('insert successful')

def randstr(n):
    
    str="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    rstr=""
    for i in range(n):
        rn=random.randint(0,61)
        rstr=rstr+str[rn]
    logging.debug(rstr)
    return rstr

def eccBase64EnHex(hex,ecclen=8):
    ecc=RSCodec(ecclen)
    try:
        en=f"{base64.b64encode(ecc.encode(bytes.fromhex(hex))).decode()}"
    except :
        
        logging.error(f"RScode编码错误！")
        raise "RScode编码错误！"
    else:
        return en
if __name__ == "__main__":
    blocksize=100
    page_=0
    db1=sqlite3.connect("D:\\markpic\\blake2.log.db",check_same_thread=False)
    db1.create_function("bl",1,eccBase64EnHex)
    cur=db1.cursor()
    while True:
        result=cur.execute(f"SELECT path from hash limit {page_*blocksize},{blocksize}")
        logging.info(result.rowcount)
        page_ +=1
        result=result.fetchall()
        list_=""
        for n in result:
            list_+=f"{n[0]},"
        print(list_)

        res=cur.execute(f"select path,hash from hash where path in ({list_})")
        res=res.fetchall()
        print(res)
        if(len(result)<=0): break
        for i in result:
            print(i)
    path=randstr(16)
    hash = hashlib.blake2b()
    hash.update(path.encode('utf-8'))
    inserts(db,path,hash.hexdigest().upper())
    db.close()
